# 构建阶段
FROM node:18.19.1-alpine3.19 AS builder

WORKDIR /app

# 设置国内Alpine镜像源
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

# 设置npm镜像
RUN npm config set registry https://registry.npmmirror.com

# 安装构建依赖
RUN apk add --no-cache python3 make g++

# 拷贝package.json和package-lock.json
COPY package.json package-lock.json* ./

# 安装依赖
RUN npm ci

# 拷贝源代码
COPY . .

# 构建应用
RUN npm run build

# 运行阶段
FROM node:18.19.1-alpine3.19

WORKDIR /app

# 设置国内Alpine镜像源
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

# 设置Go代理
ENV GOPROXY=https://goproxy.cn,direct
ENV GO111MODULE=on

# 设置npm镜像
RUN npm config set registry https://registry.npmmirror.com

# 安装运行时依赖
RUN apk add --no-cache \
    python3 \
    openjdk11 \
    go \
    rust \
    ruby \
    php \
    py3-pytest \
    py3-pylint

# 安装生产依赖
COPY package.json package-lock.json* ./
RUN npm ci --only=production

# 从构建阶段拷贝构建文件
COPY --from=builder /app/dist ./dist

# 设置环境变量
ENV NODE_ENV=production
ENV PORT=7777
ENV EXECUTION_TIMEOUT=5000
ENV MAX_BUFFER_SIZE=104857600

# 增加安全限制
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

# 暴露端口
EXPOSE 7777

# 启动应用
CMD ["node", "dist/index.js"] 